//
//  HttpClient.m
//  mlh
//
//  Created by qd on 13-5-8.
//  Copyright (c) 2013年 sunday. All rights reserved.
//

#import "LLRestEngine.h"

#import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h"

//#import "LLUtil.h"


@interface LLRestClient : AFHTTPClient

//+ (RestClient*) sharedClient;

@end

@implementation LLRestClient

//+ (AFHTTPClient*) sharedClient
//{
//    static LLRestClient *_sharedClient = nil;
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{        
//        _sharedClient = [[LLRestClient alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];
//        /*
//        [_sharedClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
//         {
//             
//            if (status == AFNetworkReachabilityStatusReachableViaWiFi)
//            {
//                [[tools shared] HUDShowHideText:@"WIFI网络" delay:1];
//            }
//            else if (status == AFNetworkReachabilityStatusReachableViaWWAN)
//            {
//                [[tools shared] HUDShowHideText:@"运营商网络" delay:1];
//            }
//            else if (status == AFNetworkReachabilityStatusNotReachable)
//            {
//                [[tools shared] HUDShowHideText:@"没有网络" delay:1];
//            }
//            else
//            {
//                [[tools shared] HUDShowHideText:@"未知网络" delay:1];
//            }
//              
//        }];
//         */
//        
//    });
//    return _sharedClient;
//}

- (id)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if (!self)
    {
        return nil;
    }
    
    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];
    
    // Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
	[self setDefaultHeader:@"Accept" value:@"application/json"];
    [self setDefaultHeader:@"Accept" value:@"text/plain"];

    
    [self setDefaultHeader:@"ostype" value:@"iphone"];
    
    
//    [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
//    [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];
//    [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"image/png"]];
//    [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"image/jpg"]];
//    [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"image/jpeg"]];
//    [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"application/json"]];
    
//    self.parameterEncoding = AFJSONParameterEncoding;
    
    return self;
}

@end

@implementation LLRestEngine

+ (instancetype)sharedInstance 
{
    static LLRestEngine *shared = nil;
    static dispatch_once_t once;
    
    dispatch_once(&once, ^{
        shared = [[LLRestEngine alloc] init];
    });
    return shared;
}

- (void)dealloc
{
    self.releaseServer = nil;
    self.testServer = nil;
    self.testSecureServer = nil;
}

- (id)init
{
    self = [super init];
    if (self != nil)
    {
        NSString *releaseServerUrl = [PxGlobal getConfig:@"ServerURL"];
        if (nil == releaseServerUrl)
            releaseServerUrl = @"http://115.236.161.69:8008";
        
        LLDLog(@"dsadas%@",releaseServerUrl);
        self.releaseServer = [[LLRestClient alloc] initWithBaseURL:[NSURL URLWithString:releaseServerUrl]];
//        self.releaseServer.parameterEncoding = AFJSONParameterEncoding; //告诉AF param是JSON格式 
        
        NSString *testServerUrl = @"http://127.0.0.1:8080";
//        NSString *testServerUrl = @"http://121.199.70.201:8080/express";
//        NSString *testServerUrl = @"http://192.168.1.97:8080/express";
//        NSString *testServerUrl = @"http://www.kked.cn";
//        NSString *testServerUrl = @"http://192.168.1.66:8080";
        self.testServer = [[LLRestClient alloc] initWithBaseURL:[NSURL URLWithString:testServerUrl]];
//        self.testServer.parameterEncoding = AFJSONParameterEncoding;
        self.testServer.allowsInvalidSSLCertificate = NO;
        
        NSString *testSecureServerUrl = @"https://127.0.0.1:8080";
        self.testSecureServer = [[LLRestClient alloc] initWithBaseURL:[NSURL URLWithString:testSecureServerUrl]];
        self.testSecureServer.allowsInvalidSSLCertificate = YES;
//        self.testSecureServer.parameterEncoding = AFJSONParameterEncoding;
//#ifdef DEBUG
//        self.testMode = YES;
//#else
        self.testMode = NO;
//#endif
    }
    return self;
}

+ (void)showWaiting:(NSString*)waitingTip
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kNetWaitingNotify
                                                        object:nil 
                                                      userInfo:@{@"msg":waitingTip}];
}

+ (void)hideWaiting
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kNetWaitingDoneNotify
                                                        object:nil];
}

+ (void)netArrorAlert:(NSString *)msg
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kNetErrorAlertNothify
                                                        object:nil
                                                      userInfo:@{@"msg":msg}];
}

+ (void)sendCommandRequest:(LLNetworkCommand*)command
{
    LLRestEngine *engine = [LLRestEngine sharedInstance];
    
    command.testMode = engine.isTestMode;
    [command prepareForSend];
    
    LLRestClient *sendClient = nil;
    if (engine.isTestMode) {
        sendClient = command.isTestSecureMode ? engine.testSecureServer : engine.testServer;
    }
    else {
        sendClient = engine.releaseServer;
    }
    
    if (command.useSystemHold)
    {
        [LLRestEngine showWaiting:command.systemHoldTip];
    }
    
    [sendClient postPath:command.pathUrl parameters:command.paramDic success:^(AFHTTPRequestOperation *operation, id JSON)
    {
        if (command.useSystemHold)
        {
            [LLRestEngine hideWaiting];
        }
        
        if ([command isUseCmdResultParser]) {
            [command handleResultObj:JSON];
            return ;
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        LLDDLog(@"%li", (long)operation.response.statusCode);
        if (operation.response.statusCode == 401) {
            if (command.useSystemHold)
            {
                [LLRestEngine hideWaiting];
            }
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"login"                                                                object:error.userInfo[@"NSLocalizedRecoverySuggestion"]];
        } else if (command.errorHandler) {
            [operation waitUntilFinished];
//            DLog(@"error:%@",error);
            command.errorHandler(error);
            
            if (command.useSystemHold)
            {
                [LLRestEngine hideWaiting];
            }
//            
            if (command.useSystemErrorAlert) 
            {
                [LLRestEngine netArrorAlert:command.systemErrorAlertTip];
            }
        }
    }];
}

@end

